package com.bey.bow.service.book;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.DateProvider;

import com.bey.bow.entity.Book;
import com.bey.bow.repository.BookDao;

@Component
@Transactional(readOnly = true)
public class BookService {

	private BookDao bookDao;

	private DateProvider dateProvider = DateProvider.DEFAULT;

	@Transactional(readOnly = false)
	public void saveBook(Book entity) {
		entity.setBookDate(dateProvider.getDate());
		bookDao.save(entity);
	}

	public Book getBook(Long id) {
		return bookDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void deleteBook(Long id) {
		bookDao.delete(id);
	}

	public Page<Book> getBooks(int pageNumber, int pageSize, String sortType) {

		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize,
				sortType);
		return bookDao.findAll(pageRequest);

	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize,
			String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("date".equals(sortType)) {
			sort = new Sort(Direction.DESC, "bookDate");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	@Autowired
	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}

}
